# coding:utf8
'''
 admin 相关
'''
from flask_restful import request, Resource
from _sys.models import MongodbOperations, Token, ResponseJson, CreateId, FormatIO
from _sys.parser import parsers
from _sys.function import admin_open_ips, had_power, md5Encode, parse_param_info, allow_cross, format_words
from _sys.code import dbNameDict


import time

mgOp = MongodbOperations()
token = Token()
responseJson = ResponseJson()
ctId = CreateId()

class Admin(Resource):
    '''
        /a/a
    '''
    @allow_cross
    def get(self):
        '''
            获取管理员信息
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(a_token, a_id):
            return responseJson.error_response(code='tokenFailure')

        try:
            a_data = mgOp.find_one(dbNameDict['adminData'], filter={'a_id':a_id, 'status':'1'})
            login_data = mgOp.find_many(dbNameDict['adminOperationData'], filter={'a_id': a_id, 'type' : 'login'}, sort='create_time')
            if a_data:
                rd = {
                    'aId': a_data['a_id'],
                    'aName': a_data['a_name'],
                    'aMail': a_data['a_mail'],
                    'aPhone': a_data['a_phone'],
                    'aRole': a_data['a_role'],
                    'formatTime': a_data['format_time'],
                    'lastLoginTime': login_data[0]['format_time'],
                    'lastLoginIp': login_data[0]['op_ip'],
                    'loginData': login_data
                }
                return responseJson.correct(code='ok', data=rd)
            else:
                return responseJson.error_response(code='accountOrPasswordError')
        except Exception:
            return responseJson.error_response(code='unknownError')

    @allow_cross
    def post(self):
        '''
            管理员登录
        :return:
        '''
        args = parsers()
        a_mail = args.get('a_mail')
        a_pwd = args.get('a_pwd')
        a_ip = request.remote_addr
        a_id = args.get('a_id')
        a_token = args.get('a_token')

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if a_id and a_token:  # token登录
            if token.verify(a_token, a_id):
                # 有触动行为 token 应当予以更新
                new_token = token.create(a_id)
                rd = {
                    'aId': a_id,
                    'aToken': new_token
                }
                return responseJson.correct(code='ok',data=rd)
            else:
                return responseJson.error_response(code='tokenFailure')

        my_id = ctId.uid(a_mail)
        rd = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': my_id})
        if rd:   # 账号存在
            if rd['a_pwd'] == md5Encode(a_pwd) and rd['status'] == '1':  # 密码对应  状态正常
                a_token = token.create(my_id)
                a_id = my_id
                a_op = {
                    'type':'login',
                    'create_time': str(time.time()),
                    'a_id': a_id,
                    'format_time': FormatIO().timestamp_format(time.time()),
                    'op_ip': str(a_ip)
                }
                rd = {
                    'aId': a_id,
                    'aName': rd['a_name'],
                    'aToken': a_token
                }
                mgOp.insert_one(dbNameDict['adminOperationData'], a_op) # 添加admin 操作记录
                return responseJson.correct(code='ok', data=rd)
            else:
                return responseJson.error_response(code='accountOrPasswordError')   # 密码错误或者状态失效
        else:  # 账号不存在
            return responseJson.error_response(code='accountOrPasswordError')

    @allow_cross
    def put(self):
        '''
            新增管理员
            管理员无法自主注册 由具有权限的管理员注册
        :return:
        '''
        args =parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr

        a_name = args.get('a_name')   # 管理员名
        a_mail = args.get('a_mail')   # 管理员邮箱
        a_pwd = args.get('a_pwd')     # 管理员密码
        a_role = args.get('a_role')   # 管理员角色
        a_phone = args.get('a_phone')  # 管理员手机号

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if a_role == 'observer':    # 观察者
            if not had_power('Allocate1LevelPermissions', powers):  # 不具权限
                return responseJson.error_response(code='permissionsValidationFailure')

        elif a_role == 'regionalAdmin':    # 条线管理员
            if not had_power('Allocate2LevelPermissions', powers):  # 不具权限
                return responseJson.error_response(code='permissionsValidationFailure')

        elif a_role == 'admin':    # 管理员
            if not had_power('Allocate3LevelPermissions', powers):  # 不具权限
                return responseJson.error_response(code='permissionsValidationFailure')
        else:
            return responseJson.error_response(code='lackOfNecessaryParameters')

        may_a_id = ctId.uid(a_mail)   # 可能的id
        if mgOp.find_one(dbNameDict['adminData'], filter={'a_id':may_a_id}):  # 邮箱已被注册
            return responseJson.error_response(code='mailboxHasBeenUsed')

        role_data = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_name': a_role})

        new_admin_data = {
            'a_id': may_a_id,
            'a_name': a_name,
            'a_mail': a_mail,
            'a_pwd': md5Encode(a_pwd),
            'a_phone': a_phone,
            'a_role_id': role_data['role_id'],
            'a_role': a_role,
            'create_time': str(time.time()),
            'format_time': FormatIO().timestamp_format(time.time()),
            'create_admin':a_id,
            'status': '1'    # 0 表示废弃  1 表示正常
        }

        if mgOp.insert_one(dbNameDict['adminData'], new_admin_data):
            return responseJson.correct(code='ok', data={'msg':'新增'+a_role+'成功'})

    @allow_cross
    def delete(self):
        '''
            修改管理员信息  -- 接口不太贴切
            管理员自身无法进行信息修改 必须寻找上级管理员
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        a_name = args.get('a_name')  # 管理员名
        a_phone = args.get('a_phone')  # 管理员手机号

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        new_data = {}
        if a_name:
            new_data['a_name'] = a_name
        if a_phone:
            new_data['a_phone'] = a_phone
        if new_data:
            try:
                mgOp.update_one(dbNameDict['adminData'], filter={'a_id':a_id}, data=new_data)
                return responseJson.correct(code='ok',data={'msg':'更新用户数据成功'})
            except Exception:
                return responseJson.error_response(code='lackOfNecessaryParameters')
        else:
            return responseJson.error_response(code='lackOfNecessaryParameters')

class Role(Resource):
    '''
       /a/r
       角色权限操作
       -- get  获取角色权限表
       -- post 修改觉得权限表
       -- put  保留接口
       -- delete 保留接口
   '''

    @allow_cross
    def get(self):
        '''
            获取角色权限表
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanGetAdminRoleList', powers):
            return responseJson.error_response(code='permissionsValidationFailure')

        role_list = mgOp.find_many(dbNameDict['adminRoleData'], filter={})
        return responseJson.correct(code='ok', data=role_list)

    @allow_cross
    def post(self):
        '''
            修改觉得权限表
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        role_id = args.get('role_id')   # 针对修改的角色
        role_powers = args.get('role_powers')    # 角色对应权限  SSSS|ssss|asssa  形式

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanModifyAdminRole', powers):
            return responseJson.error_response(code='permissionsValidationFailure')
        new_data = {
            'powers': parse_param_info(role_powers)
        }
        if mgOp.update_one(dbNameDict['adminRoleData'], filter={'role_id':role_id}, data=new_data):
            return responseJson.correct(code='ok', data={'msg':'修改角色权限成功'})
        else:
            return responseJson.error_response(code='unknownError')

    @allow_cross
    def put(self):
        return responseJson.error_response(code='RequestMethodError')

    @allow_cross
    def delete(self):
        return responseJson.error_response(code='RequestMethodError')


class Power(Resource):
    '''
        /a/power
        管理员权限相关
        -- get 获取权限列表
        -- post 修改权限表项
        -- put  新增权限表项
        -- delete 删除权限表项
    '''
    @allow_cross
    def put(self):
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        intro = args.get('intro')  #
        name = args.get('name')   # CanGetUsersList

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        if mgOp.find_one(dbNameDict['adminPowersData'], filter={'power_name': name}):
            return responseJson.error_response(code='resourcesHadExist')

        role_name = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role']
        if role_name == 'superAdmin':   # 需要superAdmin
            new_data = {
                "power_name": name,
                "intro":intro,
                "create_time":str(time.time()),
                "a_id": a_id
            }
            try:
                mgOp.insert_one(dbNameDict['adminPowersData'],new_data)  # 添加权限
                ops = {
                    'name':'新增了名为'+name+'的权限',
                    'type':'power',
                    'a_id':a_id,
                    'create_time':str(time.time()),
                    'format_time':FormatIO().timestamp_format(time.time()),
                    'op_ip':a_ip
                }
                mgOp.insert_one(dbNameDict['adminOperationData'], ops)
                return responseJson.correct(code='ok', data={'msg':'新增权限成功'})
            except Exception:
                return responseJson.error_response(code='unknownError')
        else:
            return responseJson.error_response(code='permissionsValidationFailure')  # 不具权限

    @allow_cross
    def get(self):
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        name = args.get('name')

        if not admin_open_ips(a_ip):  # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):  # token 失效
            return responseJson.error_response(code='tokenFailure')

        if name:
            try:
                power = mgOp.find_one(dbNameDict['adminPowersData'], filter={'power_name':name})
                return responseJson.correct(code='ok', data=power)
            except Exception:
                return responseJson.error_response(code='unknownError')
        else:
            try:
                powers = mgOp.find_many(dbNameDict['adminPowersData'],filter={})
                return responseJson.correct(code='ok', data=powers)
            except Exception:
                return responseJson.error_response(code='unknownError')

    @allow_cross
    def post(self):

        return responseJson.error_response(code='RequestMethodError')

    @allow_cross
    def delete(self):
        '''
            删除权限
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        name = args.get('name')

        if not admin_open_ips(a_ip):  # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):  # token 失效
            return responseJson.error_response(code='tokenFailure')

        role_name = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['role_name']
        if role_name == 'superAdmin':
            try:
                mgOp.delete_one(dbNameDict['adminPowersData'], filter={'power_name':name})
                ops = {
                    'name': '删除了名为' + name + '的权限',
                    'a_id': a_id,
                    'ip': a_ip,
                    'create_time': str(time.time())
                }
                mgOp.insert_one(dbNameDict['adminOperationData'], ops)
                return responseJson.correct(code='ok', data={'msg':'删除权限成功'})
            except Exception:
                return responseJson.error_response(code='unknownError')


class AUser(Resource):
    '''
        /a/au
        admin 对user 操作
    '''
    @allow_cross
    def get(self):
        '''
            获取user列表或具体项
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        u_id = args.get('u_id')
        u_name = args.get('u_name')
        pg = args.get('pg')
        num = args.get('num')
        status = args.get('status')
        start_t = args.get('start_t')
        end_t = args.get('end_t')

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanGetUsersList', powers):
            return responseJson.error_response(code='permissionsValidationFailure')

        if u_id:
            try:
                rd = mgOp.find_one(dbNameDict['userData'], filter={'u_id':u_id})
                login_record = mgOp.find_many(dbNameDict['userLoginData'], filter={'u_id':u_id, 'u_status':status}, sort='create_time')
                rd['login_record'] = login_record
                rd['last_login_time'] = login_record[0]['format_time']
                rd['last_login_ip'] = login_record[0]['u_ip']
                return responseJson.correct(code='ok',data=rd)
            except Exception:
                return responseJson.error_response(code='unknownError')
        else:
            if not pg:
                pg = 1
            if not num:
                num = 24
            pg = int(pg)
            num = int(num)
            query = {'u_status':status}
            if start_t:
                query['create_time'] = {
                    "$gte": str(time.mktime(time.strptime(start_t,"%Y-%m-%d-%H:%M:%S")))
                }
            if end_t:
                query['create_time']['$lte'] = str(time.mktime(time.strptime(end_t,"%Y-%m-%d-%H:%M:%S")))
            if u_name:
                query = {'u_name':u_name}
            try:
                rds = mgOp.find_many(dbNameDict['userData'], query)
                temp = {
                    'data': rds[(pg-1)*num : pg*num],
                    'count':len(rds)
                }
                return responseJson.correct(code='ok', data=temp)
            except Exception:
                return responseJson.error_response(code='unknownError')

    @allow_cross
    def post(self):
        '''
            用户信息修改 --目前只开放用户账号封停
        :return:
        '''
        args = parsers()
        a_id= args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        u_id = args.get('u_id')
        status = args.get('status')

        if not admin_open_ips(a_ip):  # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):  # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanDiscardUser', powers):
            return responseJson.error_response(code='permissionsValidationFailure')

        try:
            mgOp.update_one(dbNameDict['userData'],filter={'u_id':u_id}, data={'u_status': status})
            return responseJson.correct(code='ok', data={'msg':'修改用户状态成功'})
        except Exception:
            return responseJson.error_response(code='unknownError')
















